package qs.openxt.libs.qrcode;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.zxing.Result;
import com.mining.app.zxing.camera.IMECameraManager;
import com.mining.app.zxing.decoding.IMECaptureActivityHandler;
import com.mining.app.zxing.decoding.InactivityTimer;
import com.mining.app.zxing.view.IMEViewfinderView;

import qs.openxt.libs.R;
import qs.openxt.libs.fragment.BaseActivity;
import qs.openxt.libs.progress.Wait;
import qs.openxt.libs.qrcode.QrcodeTasking.OnScanningActionListener;
import qs.openxt.libs.util.StringUtil;

public class QrcodeCaptureActivity extends BaseActivity implements View.OnClickListener, OnScanningActionListener {

	private IMECaptureActivityHandler handler;
	private IMEViewfinderView viewfinderView;
	private InactivityTimer inactivityTimer;
	private boolean led_is_open = false;
	private ImageView qrcode_scan_tv_code = null, qrcode_scan_tv_photo = null, qrcode_scan_tv_led = null;

	private static final int REQUEST_CODE = 0x001;
	
	private boolean hasSurface;
	
	private Activity mActivity = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		customStyle(R.layout.qrcode_scan, "二维码/条形码", true);
		
		mActivity = this;

		viewfinderView = (IMEViewfinderView) findViewById(R.id.qrcode_viewfinder_view);
		qrcode_scan_tv_code = (ImageView) findViewById(R.id.qrcode_scan_tv_code);
		qrcode_scan_tv_photo = (ImageView) findViewById(R.id.qrcode_scan_tv_photo);
		qrcode_scan_tv_led = (ImageView) findViewById(R.id.qrcode_scan_tv_led);
		qrcode_scan_tv_code.setOnClickListener(this);
		qrcode_scan_tv_photo.setOnClickListener(this);
		qrcode_scan_tv_led.setOnClickListener(this);
		
		hasSurface = false;
		IMECameraManager.init(getApplication());
		inactivityTimer = new InactivityTimer(this);
		
		viewfinderView.setVisibility(View.GONE);
	}
	
	private void load(){
		Wait.sharedInstance().start(this, null);
		
		doInit();
	}
	
	private void doInit(){
		IMECameraManager.get().offLight();
		if (handler != null) {
			handler.quitSynchronously();
			handler = null;
		}
		SurfaceView surfaceView = (SurfaceView) findViewById(R.id.qrcode_preview_view);
		SurfaceHolder surfaceHolder = surfaceView.getHolder();
		if (hasSurface) {
			initCamera(surfaceHolder);

			Wait.sharedInstance().stop();
		}else{
			surfaceHolder.addCallback(new Callback() {
				@Override
				public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
	
				}
	
				@Override
				public void surfaceCreated(final SurfaceHolder holder) {
					QrcodeLoading loading = new QrcodeLoading(mActivity, new QrcodeLoading.OnActionListener() {
						public void onActionCompleted() {
							if (!hasSurface) {
								hasSurface = true;
								initCamera(holder);
							}
							initCamera(holder);
							Wait.sharedInstance().stop();
						}
					});
					loading.doRequest();
				}
	
				@Override
				public void surfaceDestroyed(SurfaceHolder holder) {
					hasSurface = false;
				}
			});
			surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		load();
	}

	@Override
	protected void onPause() {
		Wait.sharedInstance().stop();
		
		IMECameraManager.get().offLight();
		
		if (handler != null) {
			handler.quitSynchronously();
			handler = null;
		}
		IMECameraManager.get().closeDriver();
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		Wait.sharedInstance().stop();
		if (handler != null) {
			handler.quitSynchronously();
			handler = null;
		}
		if(inactivityTimer != null)
			inactivityTimer.shutdown();
		IMECameraManager.get().offLight();
		IMECameraManager.get().closeDriver();
		super.onDestroy();
	}

	/**
	 * 处理扫描结果
	 * 
	 * @param result
	 * @param barcode
	 */
	public void handleDecode(Result result, Bitmap barcode) {
		inactivityTimer.onActivity();
		String resultString = result.getText();
		onResultHandler(resultString, barcode);
	}

	private void initCamera(SurfaceHolder surfaceHolder) {
		try {
			IMECameraManager.get().openDriver(surfaceHolder);
		} catch (Exception e) {
			return;
		}
		if (handler == null) {
			handler = new IMECaptureActivityHandler(this, null, null);
		}
		
		viewfinderView.setVisibility(View.VISIBLE);
	}

	public IMEViewfinderView getViewfinderView() {
		return viewfinderView;
	}

	public Handler getHandler() {
		return handler;
	}

	public void drawViewfinder() {
		viewfinderView.drawViewfinder();
	}

	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.qrcode_scan_tv_code) {
			
		} else if (v.getId() == R.id.qrcode_scan_tv_photo) {
			Intent innerIntent = new Intent(Intent.ACTION_GET_CONTENT);
			/*
			if (Build.VERSION.SDK_INT < 19) {
				innerIntent.setAction(Intent.ACTION_GET_CONTENT);
			} else {
				innerIntent.setAction(Intent.ACTION_OPEN_DOCUMENT);
			}*/
			innerIntent.setType("image/*");
			Intent wrapperIntent = Intent.createChooser(innerIntent, "选择二维码图片");
			startActivityForResult(wrapperIntent, REQUEST_CODE);
		} else if (v.getId() == R.id.qrcode_scan_tv_led) {
			try {
				if (led_is_open) {
					IMECameraManager.get().offLight();
					led_is_open = false;
				} else {
					IMECameraManager.get().openLight();
					led_is_open = true;
				}
			} catch (Exception e) {
				led_is_open = false;
			}
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case REQUEST_CODE:
				// 获取选中图片的路径
				Cursor cursor = null;
				try{
					String photo_path = null;
					cursor = getContentResolver().query(data.getData(), null, null, null, null);
					if (cursor.moveToFirst()) {
						photo_path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
					}
					cursor.close();
					QrcodeTasking qrcodeTask = new QrcodeTasking(this);
					qrcodeTask.setOnScanningActionListener(this);
					qrcodeTask.doRequest(photo_path);
				}catch (Exception e) {
					Toast.makeText(this, "扫描二维码错误！", Toast.LENGTH_SHORT).show();
				}finally{
					if(cursor != null)
						cursor.close();
				}
				break;
			}
		}
	}

	/**
	 * 跳转到上一个页面
	 * 
	 * @param resultString
	 * @param bitmap
	 */
	private void onResultHandler(final String resultString, Bitmap bitmap) {
		if (StringUtil.isNull(resultString)) {
			Toast.makeText(this, "扫描二维码错误！", Toast.LENGTH_SHORT).show();
			return;
		}
		
		Intent data = new Intent();
		data.putExtra("code", resultString);
		setResult(RESULT_OK, data);
		finish();
	}

	@Override
	public void onScanningActionCompleted(String result) {
		onResultHandler(result, null);
	}

	@Override
	public void onScanningActionFailed() {
		Toast.makeText(this, "扫描二维码错误！", Toast.LENGTH_SHORT).show();
	}
}